import React from "react";
import { createSchemaField } from "@formily/react";
import localStorage from "store2";
import api from "src/http/api";
import { StorageProps } from "src/utils/interface";

import {
  FormDialog,
  FormLayout,
  FormItem,
  Input,
  Select,
  ArrayItems,
  FormGrid,
} from "@formily/antd";
import { Button, notification } from "antd";
import { ImportOutlined, EditOutlined } from "@ant-design/icons";
import ArrayRemoveBtn from "src/components/ArrayRemoveButton";
import OwnersSelect from "src/components/OwnersSelect";
import getSchema from "./schema";

interface Props {
  id: string;
  type: string;
  style?: React.CSSProperties;
  storageUri?: string;
  setTableData: React.Dispatch<React.SetStateAction<StorageProps[]>>;
}

const OpenStorageFormButton: React.FC<Props> = (props) => {
  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Input,
      Select,
      OwnersSelect,
      ArrayItems,
      FormLayout,
      FormGrid,
      ArrayRemoveBtn,
    },
  });

  const schema = getSchema(props.type);

  const settings =
    props.type === "add"
      ? { title: "创建 Storage", icon: <ImportOutlined />, buttonText: "新建" }
      : { title: "编辑 Storage", icon: <EditOutlined />, buttonText: "编辑" };

  const handleClick = () => {
    FormDialog(settings.title, props.id, (form) => {
      return (
        <FormLayout labelCol={6} wrapperCol={16}>
          <SchemaField schema={schema} />
          <FormDialog.Footer>
            <Button
              type="primary"
              danger
              style={{ float: "left" }}
              onClick={() => form.reset()}
            >
              Reset
            </Button>
          </FormDialog.Footer>
        </FormLayout>
      );
    })
      .forOpen((form, next) => {
        // 创建 Storage
        if (props.type === "add") {
          return next({
            initialValues: localStorage.get("storage"),
          });
        }

        // 编辑 Storage
        api.getStorageByStorageUri(`${props.storageUri}`).then((res: any) => {
          const initialValues = res.data;
          const temp = res.data.storageUri.split("-");
          initialValues.namespace = temp[0];
          initialValues.name = temp[2];
          res.data.storageUri.split("-");
          next({
            initialValues,
          });
        });
      })
      .forConfirm((form, next) => {
        // 创建 Storage
        if (props.type === "add") {
          return api
            .addStorage(form.values)
            .then(async () => {
              if (props.type === "add") {
                localStorage.remove("storage");
              }
              await api.getStorage().then((res: any) => {
                props.setTableData(res.data);
              });

              notification.success({
                message: "Success",
                description: "创建 storage 成功",
              });
              next(form);
            })
            .catch(() => {
              form.setSubmitting(false);
            });
        }

        // 编辑 Storage
        api
          .editStorage(form.values)
          .then(async () => {
            if (props.type === "add") {
              localStorage.remove("storage");
            }
            await api.getStorage().then((res: any) => {
              props.setTableData(res.data);
            });

            notification.success({
              message: "Success",
              description: "编辑 storage 成功",
            });
            next(form);
          })
          .catch(() => {
            form.setSubmitting(false);
          });
      })
      .forCancel((form, next) => {
        // 退出时，保存表单的值
        if (props.type === "add") {
          localStorage.set("storage", form.values);
        }
        next(form);
      })
      .open()
      .then(console.log)
      .catch(console.error);
  };

  return (
    <FormDialog.Portal id={props.id}>
      <Button
        style={props.style}
        type="primary"
        icon={settings.icon}
        onClick={handleClick}
      >
        {settings.buttonText}
      </Button>
    </FormDialog.Portal>
  );
};

export default OpenStorageFormButton;
